package org.rainwalk.bill.util;

import cn.hutool.core.io.IoUtil;
import org.mozilla.universalchardet.UniversalDetector;
import org.rainwalk.bill.api.exception.BizException;
import org.rainwalk.bill.api.model.ResponseCode;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

public class EncodeUtil {

    public static Charset getEncode(MultipartFile file) {
        UniversalDetector detector = new UniversalDetector(null);
        try (InputStream is = file.getInputStream()){
            final byte[] bytes = IoUtil.readBytes(is);
            detector.handleData(bytes, 0, bytes.length);
            detector.dataEnd();
            return Charset.forName(detector.getDetectedCharset());
        } catch (IOException e) {
            throw new BizException(ResponseCode.PARAMS_VERITY_FAIL, "文件编码获取失败");
        }
    }
}
